import apiClient from "./interceptor";

// 岗位类型定义
export interface Position {
  positionNumber: string;
  positionName: string;
  positionProperties: string;
  jobDescription: string;
  deptType: number;
  deptId: number;
}

// 通用响应接口
interface ApiResponse<T> {
  code: number;
  msg: string;
  data?: T;
}

// 新增岗位
export const createPosition = async (positionData: Position) => {
  try {
    const response = await apiClient.post<ApiResponse<any>>('/department/position', positionData);
    
    if (response.data.code === 1) {
      return response.data;
    } else {
      const errorMsg = response.data.msg || "创建岗位失败";
      console.error("创建岗位失败:", {
        message: errorMsg,
        data: response.data
      });
      throw new Error(errorMsg);
    }
  } catch (error: any) {
    console.error("创建岗位失败:", error);
    if (error.response) {
      throw new Error(
        error.response.data?.message || 
        error.response.data?.msg || 
        "服务器返回错误"
      );
    } else if (error.request) {
      throw new Error("服务器未响应");
    } else {
      throw error;
    }
  }
};

// 添加更新岗位的接口
export interface UpdatePositionParams {
    positionId: number;
    positionNumber?: string;
    positionName?: string;
    positionProperties?: string;
    jobDescription?: string;
    person?: number;
    deptType?: number;
    deptId?: number;
    professionalSkillsRight: number;
    communicationSkillsRight: number;
    teamworkAbilityRight: number;
  }
  
  // 更新岗位
  export const updatePosition = async (updateData: UpdatePositionParams) => {
    try {
      console.log("发送更新岗位请求，数据:", JSON.stringify(updateData, null, 2));
      const response = await apiClient.patch<ApiResponse<any>>('/department/position', updateData);
      console.log("后端响应:", JSON.stringify(response, null, 2));
  
      if (response?.data?.code === 1) {
        return response.data;
      } else {
        const errorMsg = response?.data?.msg || "更新岗位失败";
        console.error("更新岗位失败:", {
          message: errorMsg,
          data: response?.data
        });
        throw new Error(errorMsg);
      }
    } catch (error: any) {
      console.error("更新岗位失败:", error);
      if (error.response) {
        throw new Error(
          error.response.data?.message || 
          error.response.data?.msg || 
          "服务器返回错误"
        );
      } else if (error.request) {
        throw new Error("服务器未响应");
      } else {
        throw error;
      }
    }
  };

/**
 * 删除岗位
 * @param positionIds 岗位ID，可以是单个ID或多个ID的数组
 * @returns 删除结果
 */
export const deletePosition = async (positionIds: string | number) => {
  try {
    // 将参数转换为字符串
    const positionIdsStr = String(positionIds);
    
    const response = await apiClient.delete(`/position/${positionIdsStr}`);
    
    if (response.data && response.data.code === 1) {
      return response.data;
    } else {
      const errorMsg = response.data.msg || "删除岗位失败";
      console.error("删除岗位失败:", {
        message: errorMsg,
        data: response.data
      });
      throw new Error(errorMsg);
    }
  } catch (error: any) {
    console.error("删除岗位失败:", error);
    if (error.response) {
      throw new Error(
        error.response.data?.message || 
        error.response.data?.msg || 
        "服务器返回错误"
      );
    } else if (error.request) {
      throw new Error("服务器未响应");
    } else {
      throw error;
    }
  }
};

// 部门岗位员工查询参数接口
export interface DepartmentPersonParams {
  page?: number;
  pageSize?: number;
  deptId: number;
  deptType: number; // 部门类型（1职能部门，2二级学院，3教辅单位（其他部门））
  positionId: number;
}

// 部门岗位员工数据项接口
export interface DepartmentPersonItem {
  employeeId: string;
  name: string;
  onboardingTime: string;
}

// 部门岗位员工响应数据接口
export interface DepartmentPersonData {
  total: number;
  row: DepartmentPersonItem[];
}

/**
 * 查询部门下各个岗位的员工
 * @param params 查询参数
 * @returns 部门岗位员工数据
 */
export const getDepartmentPersons = async (params: DepartmentPersonParams): Promise<ApiResponse<DepartmentPersonData>> => {
  try {
    // 打印请求参数
    console.log("查询部门岗位员工请求参数:", params);
    
    const response = await apiClient.get<ApiResponse<DepartmentPersonData>>('/department/person', { params });
    
    // 打印响应数据
    console.log("查询部门岗位员工响应:", response.data);
    
    if (response.data.code === 1) {
      return response.data;
    } else {
      const errorMsg = response.data.msg || "查询部门岗位员工失败";
      console.error("查询部门岗位员工失败:", {
        message: errorMsg,
        data: response.data
      });
      throw new Error(errorMsg);
    }
  } catch (error: any) {
    console.error("查询部门岗位员工失败:", error);
    if (error.response) {
      throw new Error(
        error.response.data?.message || 
        error.response.data?.msg || 
        "服务器返回错误"
      );
    } else if (error.request) {
      throw new Error("服务器未响应");
    } else {
      throw error;
    }
  }
};

/**
 * 查询特定部门特定岗位的员工
 * @param deptId 部门ID
 * @param deptType 部门类型
 * @param positionId 岗位ID
 * @param page 页码
 * @param pageSize 每页记录数
 * @returns 部门岗位员工数据
 */
export const getPositionEmployees = async (
  deptId: number,
  deptType: number,
  positionId: number,
  page: number = 1,
  pageSize: number = 10
): Promise<ApiResponse<DepartmentPersonData>> => {
  const params: DepartmentPersonParams = {
    deptId,
    deptType,
    positionId,
    page,
    pageSize
  };
  
  return getDepartmentPersons(params);
};

/**
 * 获取部门所有岗位的员工（分页）
 * @param deptId 部门ID
 * @param deptType 部门类型
 * @param page 页码
 * @param pageSize 每页记录数
 * @returns 部门所有岗位员工数据
 */
export const getAllPositionEmployees = async (
  deptId: number,
  deptType: number,
  page: number = 1,
  pageSize: number = 10
): Promise<ApiResponse<DepartmentPersonData>> => {
  // 假设positionId为0表示获取所有岗位
  // 实际使用时可能需要根据后端API调整
  const params: DepartmentPersonParams = {
    deptId,
    deptType,
    positionId: 0, // 0表示所有岗位，具体值需要根据后端API确定
    page,
    pageSize
  };
  
  return getDepartmentPersons(params);
};